package com.brayan.webapp.controller.realestate;

import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

import org.joda.time.LocalDate;

import com.brayan.webapp.model.realestate.Costs;
import com.brayan.webapp.service.realestate.ReservationBean;

@Path("/")
@Consumes({ "application/json" })
@Produces({ "application/json" })
public class ReservationResource {

	@Inject
	ReservationBean resService;

	public ReservationResource() {

	}

	@GET
	@Path("reservation/costs/{numberOfGuests}/{startDate}/{endDate}")
	public Costs getTotalCosts(@PathParam("numberOfGuests") int numberOfGuests,
			@PathParam("startDate") String startDateStr,
			@PathParam("endDate") String endDateStr) throws Exception {
		
		LocalDate startDate = null;
		LocalDate endDate = null;

		try {
			startDate = convertToDate(startDateStr);
			endDate = convertToDate(endDateStr);
			
			if(startDate.compareTo(endDate) >= 0)
				throw new Exception("Start date of reservation period must be less than the end date.");
				
		} catch (Exception ex) {
			// TODO log as error
			throw new Exception(
					"Failed to convert dates or a period. Strings are "
							+ startDateStr + ", " + endDateStr+". " + ex.getMessage());
		}

		Costs costs = resService.calculateCosts(numberOfGuests, startDate,
				endDate);
		return costs;
	}

	/**
	 * 
	 * @param dateStr
	 *            Expect format: yyyy-MM-dd
	 * @return Returns LocalDate or throws an exception.
	 */
	private LocalDate convertToDate(String dateStr) {
		int year = Integer.parseInt(dateStr.substring(0, 4));
		int month = Integer.parseInt(dateStr.substring(5, 7));
		int day = Integer.parseInt(dateStr.substring(8, 10));

		LocalDate localDate = new LocalDate(year, month, day);
		return localDate;
	}

}